package com.itheima.utils;

import com.mysql.jdbc.StringUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

public class MapperProxyFactory implements InvocationHandler {

    private DefaultSession defaultSession;

    public MapperProxyFactory(DefaultSession defaultSession) {
        this.defaultSession = defaultSession;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.println("invoke--->"+args);
        String className = method.getDeclaringClass().getName();
        String methodName = method.getName();

        Class<?> declaringClass = method.getDeclaringClass();

        boolean annotationSelectPresent = method.isAnnotationPresent(Select.class);
        boolean annotationInsertPresent = method.isAnnotationPresent(Insert.class);
        boolean annotationUpdatePresent = method.isAnnotationPresent(Update.class);

        String statement = className+"."+methodName;
        if (annotationInsertPresent) {

            defaultSession.insert(statement, args[0]);
            return null;
        }

        if (annotationUpdatePresent) {

            defaultSession.update(statement, args[0]);
            return null;
        }

        if (annotationSelectPresent) {
            Type genericReturnType = method.getGenericReturnType();
            if (genericReturnType instanceof ParameterizedType) {

                return defaultSession.select(statement);

            } else if (genericReturnType instanceof Type) {

                return defaultSession.selectOne(statement, args);
            }
        }



//        String typeName = null;
//        Type genericReturnType = method.getGenericReturnType();
//        if (genericReturnType == Void.TYPE) {
//            String statement = className+"."+methodName;
//            defaultSession.insert(statement, args[0]);
//            return null;
//        }



        return null;
    }
}
